package com.dongnao.lsn_18_classdemo;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * 侧滑菜单，完成事件分发
 */
public class MenuDrawerlayout extends DrawerLayout implements DrawerLayout.DrawerListener {
    public MenuDrawerlayout(@NonNull Context context) {
        super(context);
    }

    public MenuDrawerlayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MenuDrawerlayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        init();
    }

    private MenuContentLayout menuContentLayout;
    private MenuPutLayout putLayout;
    private View contentView;

    public void init(){
        //先获得在当前侧滑菜单下面的两个控件，一个是内容区,一个是侧滑区
        for (int i = 0; i < getChildCount();i++){
            View view = getChildAt(i);
            if(view instanceof MenuContentLayout){
                menuContentLayout = (MenuContentLayout) view;
            }else{
                contentView = view;
            }
        }

        //偷天换日
        removeView(menuContentLayout);
        Log.i("barry","menuContentLayout:"+menuContentLayout);

        //新建组合区
        putLayout = new MenuPutLayout(menuContentLayout);
        addView(putLayout);

        addDrawerListener(this);

    }

    float y;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        y = ev.getY();
        if(ev.getAction() == MotionEvent.ACTION_UP){
            closeDrawers();
            menuContentLayout.onMotionUP();
            return super.dispatchTouchEvent(ev);
        }

        if(slideOffset < 0.8){
            return super.dispatchTouchEvent(ev);
        }else{
            putLayout.setTouchY(y,slideOffset);
        }

        return super.dispatchTouchEvent(ev);
    }

    float slideOffset ;

    @Override
    public void onDrawerSlide(@NonNull View view, float slideOffset) {
        menuContentLayout.setTouchY(y,slideOffset);
        this.slideOffset  = slideOffset;
        //对内容区域进行偏移
        float translationX = view.getWidth() * slideOffset / 2 ;
        contentView.setTranslationX(translationX);
    }

    @Override
    public void onDrawerOpened(@NonNull View view) {

    }

    @Override
    public void onDrawerClosed(@NonNull View view) {

    }

    @Override
    public void onDrawerStateChanged(int i) {

    }
}
